/*
 * RoboEye - Web client for www.newocr.com that allows you
 * to recognize an image captured by the camera.
 *
 * Copyright (C) Oxygen Development, 2011
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.devoxy.roboeye.core.http;

import com.devoxy.roboeye.R;
import com.devoxy.roboeye.global.ArrayUtils;
import com.devoxy.roboeye.global.log.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Oxygen Development.
 * Author: Dmitriy Tarasov (dm.vl.tarasov@gmail.com)
 * Date: 03.06.11
 * Time: 21:17
 */
public class HttpHelper {

    private static final String TAG = HttpHelper.class.getName();

    private static final String START_TAG = "<textarea id=\"textarea\" wrap=\"off\" readonly=\"readonly\">";
    private static final String END_TAG = "</textarea>";

    public static String processImage(String pathToImage, String language, String rotation) throws IOException {
//        try {
            String languageValue = ArrayUtils.getValueFromDescription(R.array.language, R.array.language_values, language);
            String rotationValue = ArrayUtils.getValueFromDescription(R.array.rotate, R.array.rotate_values, rotation);
            HttpPost post = makePostRequest(pathToImage, languageValue, rotationValue);
            HttpResponse response = getResponse(post);
            HttpEntity entity = response.getEntity();
            return parseResponse(EntityUtils.toString(entity, "UTF-8"));
//        } catch (UnknownHostException e) {
            // TODO uncomment later
            //Log.e(TAG, "cannot connect to newocr.com", e);
//        } catch (UnsupportedEncodingException e) {
//            Log.e(TAG, "unsupported encoding", e);
//        } catch (IOException e) {
//            Log.e(TAG, "i/o exception", e);
//        }
//        return null;
    }

    private static String parseResponse(String responseString) {
        int startPos = responseString.indexOf(START_TAG) + START_TAG.length();
        int endPos = responseString.indexOf(END_TAG);
        if (startPos != -1 && endPos != -1) {
            return responseString.substring(startPos, endPos);
        } else {
            Log.e(TAG, "Error while parsing result from server = " + responseString);
            return "Error while parsing result from server";
        }
    }

    private static HttpResponse getResponse(HttpPost httpPost) throws IOException {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpClient httpclient = new DefaultHttpClient(params);
        return httpclient.execute(httpPost);
    }

    private static HttpPost makePostRequest(String pathToImage, String language, String rotation) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost("http://www.newocr.com/process.php");

        httpPost.setHeader("Referer", "http://www.newocr.com/");
        // TODO agent
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57 Safari/534.24");
        httpPost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,**/*//*;q=0.5");
        httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        httpPost.setHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
        httpPost.setHeader("Accept-Charset", "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.3\\r\\n");
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + NewocrHttpEntity.BOUNDARY);
        httpPost.setHeader("Host", "www.newocr.com");
        httpPost.setHeader("Connection", "Keep-Alive");

        NewocrHttpEntity entity = new NewocrHttpEntity(pathToImage, language, rotation);
        httpPost.setEntity(entity);

        return httpPost;
    }

}
